package com.merelyb.util;

/**
 * Created by PujiTech on 2017/7/11.
 */

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @author Nan 2015-11
 */
public class HttpClientUtil {
    private static PoolingHttpClientConnectionManager cm;
    private static String UTF_8 = "UTF-8";
    private static String sStatus = "status";
    private static String sData = "data";
    private static RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(60000).setConnectionRequestTimeout(60000)
            .setSocketTimeout(60000).build();

    private static void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(200);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(10);// 每路由最大连接数，默认值是2
        }
    }

    /**
     * 通过连接池获取HttpClient
     *
     * @return
     */
    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * GET请求
     * @param url
     * @param sEncode
     * @return
     */
    public static String httpGetRequest(String url, String sEncode) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        return getResult(httpGet, sEncode);
    }

    /**
     * GET请求
     * @param url
     * @return
     */
    public static String httpGetRequest(String url) {
        return httpGetRequest(url, UTF_8);
    }

    /**
     *GET请求
     * @param url
     * @param params
     * @param sEncode
     * @return
     * @throws URISyntaxException
     */
    public static String httpGetRequest(String url, Map<String, Object> params, String sEncode) throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        httpGet.setConfig(requestConfig);
        return getResult(httpGet, sEncode);
    }

    /**
     * GET请求
     * @param url
     * @param params
     * @return
     * @throws URISyntaxException
     */
    public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException  {
        return httpGetRequest(url, params, UTF_8);
    }

    /**
     * GET请求
     * @param url
     * @param headers
     * @param params
     * @param sEncode
     * @return
     * @throws URISyntaxException
     */
    public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params, String sEncode)
            throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        httpGet.setConfig(requestConfig);
        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet, sEncode);
    }

    /**
     * GET请求
     * @param url
     * @param headers
     * @param params
     * @return
     * @throws URISyntaxException
     */
    public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws URISyntaxException {
        return httpGetRequest(url, headers, params, UTF_8);
    }

    /**
     * POST请求
     * @param url
     * @param sEncode
     * @return
     */
    public static String httpPostRequest(String url, String sEncode) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        return getResult(httpPost, sEncode);
    }

    /**
     * POST请求
     * @param url
     * @return
     */
    public static String httpPostRequest(String url) {
        return httpPostRequest(url, UTF_8);
    }

    /**
     * POST请求
     * @param url
     * @param params
     * @param sEncode
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String httpPostRequest(String url, Map<String, Object> params, String sEncode) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        return getResult(httpPost, sEncode);
    }

    /**
     * POST请求
     * @param url
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
        return httpPostRequest(url, params, UTF_8);
    }

    /**
     * POST请求
     * @param url
     * @param headers
     * @param params
     * @param sEncode
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params, String sEncode)
            throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }

        JSONObject jsonObject =new JSONObject();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            jsonObject.put(param.getKey(), String.valueOf(param.getValue()));
        }

        StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        return getResult(httpPost, sEncode);
    }

    /**
     * POST请求
     * @param url
     * @param headers
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws UnsupportedEncodingException {
        return httpPostRequest(url, headers, params, UTF_8);
    }

    /**
     * 跨域
     * @param params
     * @return
     */
    private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }
        return pairs;
    }

    /**
     * 处理Http请求
     *
     * @param request
     * @return
     */
    private static String getResult(HttpRequestBase request, String sEncode) {
        JSONObject jsonObject = new JSONObject();
        CloseableHttpClient httpClient = getHttpClient();
        try {
            CloseableHttpResponse response = httpClient.execute(request);
            int iStatusCode = response.getStatusLine().getStatusCode();
            jsonObject.put(sStatus, iStatusCode);
            switch (iStatusCode) {
                case HttpStatus.SC_OK: {
                    //正常加载 解析数据
                    try {
                        if (response != null) {
                            HttpEntity entity = response.getEntity();
                            if (entity != null) {
                                // long len = entity.getContentLength();// -1 表示长度未知
                                jsonObject.put(sData, EntityUtils.toString(entity, sEncode));
                                response.close();
                            }
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        request.abort();
                    }
                    break;
                }
                case HttpStatus.SC_BAD_REQUEST:
                    break;
                case HttpStatus.SC_FORBIDDEN:
                    break;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //无论成不成功都要释放
            request.abort();
        }
        String sReturn  = JsonUtils.obj2Json(jsonObject);
        return sReturn;
    }

}
